%% @doc 新闻聚合数据存储

-module(newspack_store).
-export([
  register/2,
  lookup_spider/2, lookall_spider/0,
  insert_item/2, delete_items/1,
  lookall_item/1]).
-export([
         write_passwd/2
        ]).
-include_lib("stdlib/include/qlc.hrl").
-include("cloap_record.hrl").


% =========================================================
% @doc
% 注册一个新闻爬虫
% @end
% =========================================================
register(Category, Title) ->
  Fun = fun() -> mnesia:write(#news_spider{id = uuid:generate(), category = Category, title = Title}) end,
  {atomic, _} =  mnesia:transaction(Fun),
  lookup_spider(Category, Title).


lookup_spider(Category, Title) ->
  case cloap_store:do(qlc:q([Rec || Rec <- mnesia:table(news_spider),
      Rec#news_spider.category == Category, Rec#news_spider.title == Title])) of
    []         -> {error, not_found};
    [Result|_] -> {ok, Result}
  end.


lookall_spider()  ->
  cloap_store:do(qlc:q([Rec || Rec <- mnesia:table(news_spider)])).





% =========================================================
% @doc
% 加入一条新闻
% @end
% =========================================================
insert_item(SpiderId, Map) ->
  #{<<"subtitle">> := Subtitle, <<"url">> := Url, <<"update">> := Update} = Map,
  Fun = fun() -> mnesia:write(
    #news_item{
      id = uuid:generate(),
      spider_id = SpiderId,
      subtitle = Subtitle,
      url = Url,
      update = Update}) end,
  {atomic, _} =  mnesia:transaction(Fun).


lookall_item(SpiderId) ->
  cloap_store:do(qlc:q([Rec || Rec <- mnesia:table(news_item),
                Rec#news_item.spider_id == SpiderId])).


delete_items(SpiderId) ->
  [mnesia:dirty_delete(news_item, Rec#news_item.id) || Rec <- lookall_item(SpiderId)].


% =========================================================
% 口令缓存
% =========================================================

write_passwd(Login, Password) ->
    case cloap_store:find(user, {login, Login}) of
        not_found ->
            cloap_store:insert(#user{id = cloap_store:uuid(), login = Login, passwd = Password, name = Login});
        Rec ->
            cloap_store:update(Rec#user{ passwd = Password, name = Login })
    end.
